package com.example.kotlinlearn.web

import android.os.Bundle
import android.util.Log
import android.widget.ArrayAdapter
import android.widget.Toast
import com.example.kotlinlearn.BaseActivity
import com.example.kotlinlearn.MyApplication
import com.example.kotlinlearn.databinding.ActivityWebBinding
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import okhttp3.Callback
import okhttp3.OkHttpClient
import okhttp3.Request
import retrofit2.Call
import retrofit2.Response
import java.lang.Exception
import java.util.ArrayList
import kotlin.concurrent.thread

class WebActivity : BaseActivity() {
    lateinit var binding: ActivityWebBinding

    private val webData = ArrayList<String>()
    private lateinit var adapter: ArrayAdapter<String>

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityWebBinding.inflate(layoutInflater)
        setContentView(binding.root)
        adapter = ArrayAdapter(this,android.R.layout.simple_list_item_activated_1,webData)
        binding.dataList.adapter = adapter
        binding.send.setOnClickListener {
            sendRequestWithOkHttp()
        }
        binding.sendSimple.setOnClickListener {
            sendRequestWithRetrofit()
        }
    }

    private fun sendRequestWithRetrofit(){
        val webService = ServiceCreatorForWeb.create<WebService>()
        webService.getLogData("Bearer eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiLmmJPlv5fosaoiLCJjcmVhdGVk" +
                "IjoxNjIyNDU3Nzg5MDA1LCJleHAiOjE2MjMwNjI1ODl9.FSbmlRoMocdyK3h8ol_moDxS7Mzjm-jH0Q1GqniVHXR2C" +
                "AQUUAsIpoQh603etW2jBgnqFOi9VU0R2c1zDm60bg")
            .enqueue(object :retrofit2.Callback<List<log>>{
            override fun onResponse(call: Call<List<log>>, response: Response<List<log>>) {
                val list = response.body()
                if (list!=null){
                    for (log in list){
                        Log.d("Log", "onResponse: ${log.toString()}")
                    }
                }
            }

            override fun onFailure(call: Call<List<log>>, t: Throwable) {
                Toast.makeText(MyApplication.context,"获取数据失败",Toast.LENGTH_SHORT).show()
                t.printStackTrace()
            }
        })

    }
    private fun sendRequestWithOkHttp(){
        thread {
            try {
                val client = OkHttpClient()
                val request = Request.Builder()
                    .url("http://47.94.135.113:8081/system/log")
                    .addHeader("Authorization","Bearer eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiLmmJPlv5fosaoiLCJjcmVhdGVkIjoxNjIyNDU3Nzg5MDA1LCJleHAiOjE2MjMwNjI1ODl9.FSbmlRoMocdyK3h8ol_moDxS7Mzjm-jH0Q1GqniVHXR2CAQUUAsIpoQh603etW2jBgnqFOi9VU0R2c1zDm60bg")
                    .build()
                val response = client.newCall(request).execute()
                val responseData = response.body?.string()
                if (responseData!=null){
                    parseJsonWithGSON(responseData)
                }
            }catch (e:Exception){
                e.printStackTrace()
            }
        }
    }

    /**
     * json数据解析
     */
    private fun parseJsonWithGSON(jsonData:String){
        val json = Gson()
        val typeOf = object :TypeToken<List<log>>(){}.type
        val appList = json.fromJson<List<log>>(jsonData,typeOf)
        for (app in appList){
            webData.add("${app.data}\n${app.id}\n${app.name}\n${app.occurTime}\n${app.operationId}")
        }
        //更新适配器
        showResponse()
    }

    private fun showResponse(){

        runOnUiThread {
            adapter.notifyDataSetChanged()
        }
    }
}